<template>
  <div>
    <el-card>
      <div slot="header">
        <div class="flex-x gap-4 pt-2">
          <span>
            <vxe-input v-model="query.keyword" clearable :placeholder="'搜索标题'" size="medium"
              @keyup.enter.native="doSearch"></vxe-input>
          </span>
          <span>
            <el-button type="primary" plain size="small" @click="doSearch" icon="el-icon-search"
              :loading="loading">搜索</el-button>
          </span>
          <span class="flex-1"></span>
          <span>
            <el-button type="primary" size="small" @click="handleAdd" icon="el-icon-plus">
              添加样例
            </el-button>
          </span>
        </div>
      </div>

      <!-- Section Table -->
      <vxe-table stripe auto-resize ref="table" :data="dataList" :loading="loading"
        :custom-config="tableCustomConfig" align="center">
        <vxe-table-column field="id" title="ID" width="160"></vxe-table-column>
        <vxe-table-column field="collTitle" title="标题" min-width="220">
          <template v-slot="{ row }">
            <span>{{ row.collTitle }}</span>
            <el-tag v-if="!row.enabled" type="danger" size="mini" style="margin-left: 5px">未启用</el-tag>
          </template>
        </vxe-table-column>
        <vxe-table-column field="infoInputStart" title="信息录入时间" width="160">
          <template v-slot="{ row }">
            {{ formatDate(row.infoInputStart) }}<br/>
            {{ formatDate(row.infoInputEnd) }}
          </template>
        </vxe-table-column>       
        <vxe-table-column field="examStart" title="考试开始时间" width="160">
          <template v-slot="{ row }">
            {{ formatDate(row.examStart) }}<br/>
            {{ formatDate(row.examEnd) }}
          </template>
        </vxe-table-column>
        <vxe-table-column field="examMinutes" title="考试时长(分钟)" width="120"></vxe-table-column>
        <vxe-table-column field="schoolList" title="学校列表" show-overflow width="220"></vxe-table-column>
        <vxe-table-column field="gradeList" title="年级列表" show-overflow width="120"></vxe-table-column>
        <vxe-table-column field="enabled" title="启用状态" width="120">
          <template v-slot="{ row }">
            <el-switch
              v-model="row.enabled"
              @change="(val) => handleStatusChange(row, val)"
              :loading="loading"
            >
            </el-switch>
          </template>
        </vxe-table-column>
        <vxe-table-column field="randomOrder" title="题目随机顺序" width="160">
          <template v-slot="{ row }">
           <span> 随机排序：{{ row.randomOrder ? '是' : '否' }} </span><br/>
           <span> 随机范围：{{ row.randomStartNum }} - {{ row.randomEndNum }} </span>

          </template>
        </vxe-table-column>
        <vxe-table-column field="gmtCreate" title="创建时间" width="150">
          <template v-slot="{ row }">
            {{ formatDate(row.gmtCreate) }}
          </template>
        </vxe-table-column>
        <vxe-table-column field="gmtModified" title="修改时间" width="150" :visible="false">
          <template v-slot="{ row }">
            {{ formatDate(row.gmtModified) }}
          </template>
        </vxe-table-column>

        <vxe-table-column title="操作" width="170" fixed="right">
          <template v-slot="{ row }">
            <el-tooltip effect="dark" content="编辑" placement="top">
              <el-button plain circle type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(row)">
              </el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top">
              <el-button plain circle type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(row)">
              </el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="复制" placement="top">
              <el-button plain circle type="warning" size="mini" icon="el-icon-copy-document" @click="handleCopy(row)">
              </el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="客观题评分" placement="top">
              <el-button plain circle type="success" size="mini" icon="el-icon-s-claim" @click="handleObjectiveQuestionJudge(row)">
              </el-button>
            </el-tooltip>
          </template>
        </vxe-table-column>
      </vxe-table>

      <!-- Pagination -->
      <div class="flex-x justify-end mt-4 gap-4">
        <el-pagination class="page" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="query.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="query.limit"
          layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
        <el-button circle size="small" @click="handleTableCustom" icon="el-icon-menu"> </el-button>
      </div>

    </el-card>

    <EditDialog ref="editSampleDialog" @success="handleSaveSuccess" />
  </div>
</template>

<script>
import api from '@/common/api';
import SortOrderEditor from '@/components/admin/SortOrderEditor.vue';
import {DEFAULT_TABLE_CUSTOM_CONFIG} from "@/common/constants";
import EditDialog from './components/EditDialog.vue';
import time from '@/common/time';

export default {
  name: 'ItechCollList',
  components: {
    SortOrderEditor,
    EditDialog
  },
  data() {
    return {
      tableCustomConfig: DEFAULT_TABLE_CUSTOM_CONFIG,

      // List data
      dataList: [],
      loading: false,
      total: 0,
      query: {
        keyword: '',
        currentPage: 1,
        limit: 10,
      },

    };
  },
  created() {
    this.getDataList();
  },
  methods: {

    // Get section list
    async getDataList() {
      try {
        this.loading = true;
        const params = Object.assign({}, this.query);
        const {data} = await api.admin_getItechCollList(params);
        this.dataList = data.data.records;
        this.total = data.data.total;
      } finally {
        this.loading = false;
      }
    },

    // Filter operations
    doSearch() {
      this.query.currentPage = 1;
      this.getDataList();
    },

    // Handle pagination
    handleSizeChange(val) {
      this.query.limit = val;
      this.getDataList();
    },
    handleCurrentChange(val) {
      this.query.currentPage = val;
      this.getDataList();
    },
    handleTableCustom() {
      this.$refs.table?.openCustom()
    },

    // Handle CRUD operations
    handleAdd() {
      this.$refs.editSampleDialog.open({});
    },
    handleEdit(row) {
      this.$refs.editSampleDialog.open(row);
    },

    async handleCopy(row) {
      const confirmResult = await this.$confirm(`确认复制【${row.collTitle}】?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false,
        closeOnPressEscape: false
      });
      if (confirmResult !== 'confirm') {
        return;
      }

      try {
        const { value: newName } = await this.$prompt('请输入新活动的标题', '复制活动', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: `${row.collTitle} (复制)`,
          inputValidator: (val) => !!val && val.trim().length > 0,
          inputErrorMessage: '标题不能为空',
          closeOnClickModal: false,
          closeOnPressEscape: false
        });

        if (newName) {
          this.loading = true;
          await api.admin_copyItechColl({ collId: row.id, name: newName.trim() });
          this.$message.success('复制成功');
          this.getDataList();
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('复制操作失败或取消');
        }
      } finally {
        this.loading = false;
      }
    },

    async handleObjectiveQuestionJudge(row) {
      const confirmResult = await this.$confirm('确认对客观题评分?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false,
          closeOnPressEscape: false
        });
      if (confirmResult !== 'confirm') {
        return;
      }
      try {
        this.loading = true;
        await api.admin_judgeItechCollAllObjectiveQuestion(row.id);
        this.$message.success('评分完成');
        this.getDataList();
      } finally {
        this.loading = false;
      }
    },

    async handleDelete(row) {
      try {
        const confirmResult = await this.$confirm(`确认删除【${row.collTitle}】?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false,
          closeOnPressEscape: false
        });
        if (confirmResult !== 'confirm') {
          return;
        }
        await api.admin_deleteItechColl(row.id);
        this.$message.success('删除成功');
        this.getDataList();
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败');
        }
      }
    },
    async handleStatusChange(row, enabled) {
      const data = { id: row.id, enabled };
      try {
        this.loading = true;
        await api.admin_saveItechColl(data);
        this.$message.success(`更新状态成功：已${enabled ? '启用' : '禁用'}`);
        this.getDataList();
      } finally {
        this.loading = false;
      }
    },
    async handleSortUpdate(row, newValue) {
      const data = { id: row.id, sortOrder: newValue };
      try {
        this.loading = true;
        await api.admin_saveItechColl(data);
        this.$message.success('更新排序成功');
        this.getDataList();
      } finally {
        this.loading = false;
      }
    },
    handleSaveSuccess(data) {
      this.getDataList();
    },

    // Utils
    formatDate(date) {
      return time.formatDatetime(date);
    },
  }
};
</script>

<style scoped>
.filter-row span {
  margin-right: 20px;
}

.filter-row span button {
  margin-top: 5px;
  margin-bottom: 5px;
}

.filter-row span div {
  margin-top: 8px;
}

.panel-options {
  margin-top: 20px;
  text-align: right;
}

@media screen and (max-width: 768px) {
  .filter-row span {
    margin-right: 5px;
  }

  .filter-row span div {
    width: 80%;
  }
}
</style>
